const express = require('express');
const moment = require('moment');
const app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(3000);
app.use(express.static('public'));

const clients = {}

io.on('connection', function (socket) {

  // 上线通知
  socket.on('online', username => {
    if (username) {
      clients[username] = {
        socketId: socket.id,
        status: 1
      };
      console.log(clients)
    }
    socket.on('disconnect', () => {
      clients[username].status = 0;
      console.log(`${username} disconnect \n`)
    })
  });

  // 发消息
  socket.on('news', (params, fn) => {
    const receiver = clients[params.receiver];
    params.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
    if (receiver) {
      socket.to(clients[params.receiver].socketId).emit('news', params);
    } else {
      console.log(`${params.receiver} 不在线`);
    }
  });
});
